import tkinter
import tkinter.ttk as ttk
import tkinter.messagebox as messagebox
import tkinter.filedialog as filedialog
import os
import re
from main import PostProcesser


class SeaBirdDealer:
    def __init__(self):
        self.file_name = str()

    def _window(self):
        self.main_window = tkinter.Tk()
        self.main_window.title("海鸟后处理软件包")

        self.inner_title_str = tkinter.StringVar()
        self.foot_notice_str = tkinter.StringVar()

        # 控制栏
        self.mainmenu = tkinter.Menu(self.main_window)
        self.mainmenu.add_command(label="打开数据文件", command=self.open_single_file)
        self.mainmenu.add_command(label="cap转txt", command=self.open_single_file)
        self.mainmenu.add_command(label="取列", command=self.get_column)
        self.mainmenu.add_command(label="截取", command=self.data_scissor)
        # self.mainmenu.add_command(label="单文件裁切", command=self.single_file_execute)
        # self.mainmenu.add_command(label="全部裁切", command=self.mutiple_files_execute)
        self.mainmenu.add_command(label="退出", command=quit)
        self.main_window.config(menu=self.mainmenu)

        self.main_frm_width = 800
        self.main_win_height = 500

        # 左侧栏（数值预览） 预览全部数据
        left_frm = tkinter.Frame(self.main_window, borderwidth=1, relief="sunken")
        left_frm.grid(row=1, column=0, rowspan=2, sticky=tkinter.NS)
        self.search_text = tkinter.StringVar()
        sl = tkinter.Entry(left_frm, textvariable=self.search_text)
        sl.grid(row=0, column=0, columnspan=2, sticky=tkinter.EW)
        sl.bind("<Return>", self.find_in_view)
        sb = tkinter.Scrollbar(left_frm)
        sb.grid(row=1, column=1, sticky='ns')
        self.left_view = tkinter.Text(left_frm, state='disabled', width=66, height=40, yscrollcommand=sb.set)
        self.left_view.grid(row=1, column=0, sticky='nsew')
        self.left_view.tag_configure("found", background="yellow")
        sb.config(command=self.left_view.yview)
        # 上方栏（控制输入） 进行选取时间的地方
        self.main_frm = tkinter.Frame(self.main_window, borderwidth=1, relief="sunken")
        self.main_frm.grid(row=1, column=1, sticky=tkinter.NSEW)
        self.str_oprate = tkinter.StringVar()  # 工况点
        self.str_posite = tkinter.StringVar()  # 测点
        self.str_apower = tkinter.StringVar()  # 有功
        self.str_flow = tkinter.StringVar()  # 流量
        self.str_date = tkinter.StringVar()  # 日期
        self.str_hour = tkinter.StringVar()  # 时
        self.str_minute = tkinter.StringVar()  # 分
        self.str_second = tkinter.StringVar()  # 秒
        self.str_lines = tkinter.StringVar()  # 行数
        self.str_expres = tkinter.StringVar()  # 自由表达式
        row1 = tkinter.Frame(self.main_frm)
        row1.grid(row=0, column=0, sticky=tkinter.EW)
        comm_width = 30
        basic_info_entry = [
            tkinter.Label(row1, text="基础信息（用于文件命名）").grid(row=0, column=0, columnspan=4, sticky=tkinter.EW),
            tkinter.Label(row1, text="工况").grid(row=1, column=0, sticky=tkinter.EW),
            tkinter.Entry(row1, textvariable=self.str_oprate, width=comm_width).grid(row=2, column=0,
                                                                                     sticky=tkinter.EW),
            tkinter.Label(row1, text="测点").grid(row=1, column=1, sticky=tkinter.EW),
            tkinter.Entry(row1, textvariable=self.str_posite, width=comm_width).grid(row=2, column=1,
                                                                                     sticky=tkinter.EW),
            tkinter.Label(row1, text="有功").grid(row=1, column=2, sticky=tkinter.EW),
            tkinter.Entry(row1, textvariable=self.str_apower, width=comm_width).grid(row=2, column=2,
                                                                                     sticky=tkinter.EW),
            tkinter.Label(row1, text="流量").grid(row=1, column=3, sticky=tkinter.EW),
            tkinter.Entry(row1, textvariable=self.str_flow, width=comm_width).grid(row=2, column=3, sticky=tkinter.EW),
        ]
        row2 = tkinter.Frame(self.main_frm)
        row2.grid(row=1, column=0, sticky=tkinter.EW)
        time_entry = [
            tkinter.Label(row2, text="时间信息（用于裁切数据）").grid(row=0, column=0, columnspan=4, sticky=tkinter.EW),
            tkinter.Label(row2, text="日期").grid(row=1, column=0, sticky=tkinter.EW),
            tkinter.Entry(row2, textvariable=self.str_date, width=comm_width).grid(row=2, column=0, sticky=tkinter.EW),
            tkinter.Label(row2, text="时").grid(row=1, column=1, sticky=tkinter.EW),
            tkinter.Entry(row2, textvariable=self.str_hour, width=comm_width).grid(row=2, column=1, sticky=tkinter.EW),
            tkinter.Label(row2, text="分").grid(row=1, column=2, sticky=tkinter.EW),
            tkinter.Entry(row2, textvariable=self.str_minute, width=comm_width).grid(row=2, column=2,
                                                                                     sticky=tkinter.EW),
            tkinter.Label(row2, text="秒").grid(row=1, column=3, sticky=tkinter.EW),
            tkinter.Entry(row2, textvariable=self.str_second, width=comm_width).grid(row=2, column=3, sticky=tkinter.EW)
        ]
        row3 = tkinter.Frame(self.main_frm)
        row3.grid(row=2, column=0, sticky=tkinter.EW)
        btn_entry = [
            tkinter.Label(row3, text="控制面板").grid(row=0, column=0, columnspan=4, sticky=tkinter.EW),
            tkinter.Button(row3, text="检索",width=comm_width-2).grid(row=1, column=0, padx=5),
            tkinter.Button(row3, text="裁切",width=comm_width-2).grid(row=1, column=1, padx=5),
            tkinter.Button(row3, text="按钮3",width=comm_width-2).grid(row=1, column=2, padx=5),
            tkinter.Button(row3, text="按钮4",width=comm_width-2).grid(row=1, column=3, padx=5),
        ]
        #
        # tkinter.Label(row1, text="自由模式").grid(row=4, column=0, columnspan=3, sticky=tkinter.EW)
        # tkinter.Entry(row1, textvariable=self.str_expres, width=comm_width).grid(row=5, column=0, columnspan=3,
        #                                                                          sticky=tkinter.EW)
        # tkinter.Label(row1, text="行数").grid(row=4, column=3, sticky=tkinter.EW)
        # tkinter.Entry(row1, textvariable=self.str_lines, width=comm_width).grid(row=5, column=3, sticky=tkinter.EW)

        # 下方栏（绘图区域）
        self.plot_frm = tkinter.Frame(self.main_window, width=self.main_frm_width, borderwidth=1, relief="sunken")
        self.foot_lab = tkinter.Label(self.main_window, textvariable=self.foot_notice_str, anchor='w',
                                      borderwidth=1, relief="sunken")
        self.plot_frm.grid(row=2, column=1, sticky=tkinter.NSEW)
        self.foot_lab.grid(row=3, column=0, columnspan=2, sticky=tkinter.NSEW)

        self.main_window.mainloop()

    def find_in_view(self, event=None):
        self.left_view.tag_remove("found", "1.0", tkinter.END)
        f_str = self.search_text.get()
        pos = self.left_view.search(f_str, "1.0", tkinter.END)
        self.left_view.tag_add("found", pos, "%s+%dc" % (pos, len(f_str)))
        self.left_view.see(pos)

    def open_single_file(self):

        self.left_view.update()
        file_name = filedialog.askopenfilename(
            filetypes=[("CSV文件", ".csv"), ("txt文件", ".txt"), ("cap文件", ".cap"), ('All Files', '*')],
        )
        if file_name:
            self.file_name = file_name
            with open(file_name, 'rb') as f:
                lines = f.readlines()
                self.left_view.config(state='normal')
                self.left_view.tag_remove("found", "1.0", tkinter.END)
                self.left_view.delete('1.0', tkinter.END)
                for i in range(0, len(lines)):
                    self.left_view.insert(tkinter.END, lines[i])
                self.left_view.config(state='disabled')

    def _window_fresh(self):
        pass

    def get_column(self):
        pass

    def data_scissor(self):
        pass

    def single_file_execute(self):
        with open(self.str_source_file.get(), "r", encoding="utf-8") as o_f:
            self.file = o_f.read()
            self.text_plot.insert(tkinter.END, "开始读取" + o_f.name)
            self.text_plot.insert(tkinter.END, "\n")
            self.text_plot.see(tkinter.END)
            if self.str_date.get() != "" and self.str_hour.get() == "" and self.str_minute.get() == "" and self.str_second.get() == "":
                """自由模式：直接在日期栏写入正则表达式或者想要找到的行（一定是以#作为行首）"""
                self.text_plot.insert(tkinter.END, "正在以自由模式匹配……\n")
                matching = re.search(self.str_date.get() + f"(#.*\n){{{int(self.str_lines.get())}}}", self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_plot.delete("1.0", tkinter.END)
                    self.text_plot.insert(tkinter.END, self.result)
                    self.text_plot.update()
                else:
                    self.text_plot.insert(tkinter.END, "未匹配到任何数据")
            elif self.str_date.get() == "" and self.str_hour.get() != "" and self.str_minute.get() != "" and self.str_second.get() != "":
                """标准模式：在时间栏填入时分秒（24小时制）即可得到想要的行"""
                self.text_plot.insert(tkinter.END, "正在以标准模式匹配……\n")
                matching = re.search(
                    "(#.*)" + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{self.str_lines.get()}}}",
                    self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_plot.delete("1.0", tkinter.END)
                    self.text_plot.insert(tkinter.END, self.result)
                    self.text_plot.update()
                else:
                    self.text_plot.insert(tkinter.END, "未匹配到任何数据")
            elif self.str_date.get() != "" and self.str_hour.get() != "" and self.str_minute.get() != "" and self.str_second.get() != "":
                """扩展模式：在日期栏填入日期(yyyy-mm-dd)，并在时间栏填入时分秒（24小时制）即可得到想要的行"""
                self.text_plot.insert(tkinter.END, "正在以扩展模式匹配……\n")
                matching = re.search(
                    "(#.*)" + self.str_date.get() + " " + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                    self.file)
                if matching != None:
                    self.result = matching.group()
                    self.text_plot.delete("1.0", tkinter.END)
                    self.text_plot.insert(tkinter.END, self.result)
                    self.text_plot.update()
                else:
                    self.text_plot.insert(tkinter.END, "未匹配到任何数据,开始尝试第二次匹配\n")
                    date_str_list = self.str_date.get().split("-")
                    matching = re.search(
                        "(#.*)" + date_str_list[
                            2] + " Jun 2025" + "(.*)" + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                        self.file)
                    if matching != None:
                        self.result = matching.group()
                        self.text_plot.delete("1.0", tkinter.END)
                        self.text_plot.insert(tkinter.END, self.result)
                        self.text_plot.update()
                    else:
                        self.text_plot.insert(tkinter.END, "未匹配到任何数据,开始尝试第三次匹配\n")
                        matching = re.search(
                            "(#.*)" + self.str_date.get().replace("-0",
                                                                  '-') + " " + self.str_hour.get() + ':' + self.str_minute.get() + ':' + self.str_second.get() + "(.*\n)" + f"(#.*\n){{{int(self.str_lines.get())}}}",
                            self.file)
                        if matching is not None:
                            self.result = matching.group()
                            self.text_plot.delete("1.0", tkinter.END)
                            self.text_plot.insert(tkinter.END, self.result)
                            self.text_plot.update()
                        else:
                            self.text_plot.insert(tkinter.END, "未匹配到任何数据,匹配结束\n")
            self.text_plot.see(tkinter.END)


if __name__ == '__main__':
    myapp = SeaBirdDealer()
    myapp._window()
